
import serialUtil
import time
import cv2

 # IMGSIZE = (1080,1920)
IMGSIZE = (540,960)

sencenSize = (25400,15875)

scaleConf = (sencenSize[0]/540.0,sencenSize[1]/960.0)

def moveMouse(x,y,isPush = False):
    rx = int(x*scaleConf[0])
    ry = int(y*scaleConf[1])
    print('realpoint:',rx,ry)
    serialUtil.sendCmd('[%d,%d,%d]'%(rx,ry,int(isPush)))

def pushMouse(x,y):
    rx = int(x*scaleConf[0])
    ry = int(y*scaleConf[1])
    print('realpoint:',rx,ry)
    serialUtil.sendCmd('[%d,%d,1]'%(rx,ry))

def releaseMouse(x,y):
    moveMouse(x,y)

globalisPush = False

positions = []
file_path = 'point.txt'


isRoced =False

def on_EVENT_LBUTTONDOWN(event, x, y,flags, param):
        global globalisPush,positions
        # self.mPressFunc = pressMFunc        #鼠标左键按下事件
        # self.mReleaseFunc = releaseMFunc    #鼠标左键抬起事件
        # self.kPressFunc = preaseKFunc       #键盘按钮按下事件
        # self.mMoveFunc = moveMfunc          #鼠标移动事件
        #左键按下
        if event == cv2.EVENT_LBUTTONDOWN:
            # self.mPressFunc(x,y,flags)``
            print('push',x,y,flags)
            
            globalisPush = True
            if isRoced:
                dat = [x,y,int(globalisPush),time.time(),'touch']
                positions.append(dat)
            pushMouse(x,y)
        #左键抬起
        elif event == cv2.EVENT_LBUTTONUP:
            # self.mReleaseFunc(x,y,flags)
            print('release',x,y,flags)
            globalisPush = False
            if isRoced:
                dat = [x,y,int(globalisPush),time.time(),'untouch']
                positions.append(dat)
            releaseMouse(x,y)

        elif event == cv2.EVENT_MOUSEMOVE:
            # self.mMoveFunc(x,y,flags)
            print('move',x,y,flags)
            moveMouse(x,y,globalisPush)
            if globalisPush and isRoced:
                dat = [x,y,int(globalisPush),time.time(),'touchMove']
                positions.append(dat)

def write_mouse_positions_withLines():
    savestr = ''
    for i,v in enumerate(positions):
        tmpstr = str(v[0]) + ',' + str(v[1]) + ',' + str(v[2]) + ',' + '%.4f'%(v[3]) + ',' + v[4]
        savestr += tmpstr + '\n'
    savestr = savestr[:-1]
    with open(file_path, 'w') as file:
        file.writelines(savestr)

def onKey_Event(key):
    global isRoced
    print(key)
    if key == 27:    #ESC按键,退出程序
        exit(0)   
    elif key == ord('r'):
        isRoced = True
        positions.clear()
    elif key == ord('s'):
        isRoced = False
        if positions:
            write_mouse_positions_withLines()
        else:
            print('坐标数组中没有数据')
    elif key == ord('f'):
        read_from_file()
    elif key == ord('p'):
        read_from_file(repeate = True)
# 从文件中读取多行内容
def read_from_file(repeate = False):
    global positions
    with open(file_path, 'r') as file:
        txtstr = file.read()
        lines = txtstr.split('\n')
        positions = []
        for i,v in enumerate(lines):
            tmps = v.split(',')
            tmpdats = [int(tmps[0]), int(tmps[1]), int(tmps[2]), float(tmps[3])]
            positions.append(tmpdats)
    if repeate:
        while True:
            runPositions()
    else:
        runPositions()

def runPositions():
    t0 = positions[0][3]
    for i,v in enumerate(positions):
        if i == 0:
            rx = int(v[0]*scaleConf[0])
            ry = int(v[1]*scaleConf[1])
            print('realpoint:',rx,ry)
            rtype = v[2]
            serialUtil.sendCmd('[%d,%d,%d]'%(rx,ry,int(rtype)))
        else:
            dt = v[3] - t0
            t0 = v[3]
            time.sleep(dt)
            rx = int(v[0]*scaleConf[0])
            ry = int(v[1]*scaleConf[1])
            print('realpoint:',rx,ry)
            rtype = v[2]
            serialUtil.sendCmd('[%d,%d,%d]'%(rx,ry,int(rtype)))


def main():

    # touchInit()
    serialUtil.initSerial()
    global positions  
    positions = []  
    time.sleep(1)
    winname = 'name'
    cv2.namedWindow(winname)
    img = cv2.imread('m.jpg')
    cv2.setMouseCallback(winname,on_EVENT_LBUTTONDOWN)
    while True:
        cv2.imshow(winname, img)
        key = cv2.waitKey(0)
        if key:
            onKey_Event(key)

            

def test():
    serialUtil.initSerial()
    time.sleep(1)
    rx = 12135
    ry = 9822
    serialUtil.sendCmd('[%d,%d,%d]'%(rx,ry,int(1)))
    time.sleep(0.05)
    serialUtil.sendCmd('[%d,%d,%d]'%(rx,ry,int(0)))
    time.sleep(3)

if __name__ == '__main__':  
    main()
    #test()
    cv2.destroyAllWindows()